package com.faxsun.profile.core.domain;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.broadleafcommerce.profile.core.domain.AddressImpl;
import org.broadleafcommerce.profile.core.domain.Phone;
import org.broadleafcommerce.profile.core.domain.PhoneImpl;
import org.hibernate.annotations.Index;

@Entity
@Table(name = "FS_BLC_ADDRESS")
public class FSAddressImpl extends AddressImpl implements FSAddress {

	private static final long serialVersionUID = 364270796750811658L;

	@ManyToOne(targetEntity = FSReceiverImpl.class, cascade = { CascadeType.PERSIST, CascadeType.MERGE })
	@JoinColumn(name = "IDCard_PRIMARY_ID")
	@Index(name = "ADDRESS_IDCard_PRI_IDX", columnNames = { "IDCard_PRIMARY_ID" })
	protected FSReceiver receiver;

	public FSReceiver getReceiver() {
		if (receiver == null)
			receiver = new FSReceiverImpl();
		return receiver;
	}

	public void setReceiver(FSReceiver receiver) {
		this.receiver = receiver;
	}

	public boolean getIsDefault() {
		return isDefault;
	}

	@Override
	public Phone getPhonePrimary() {
		Phone legacyPhone = new PhoneImpl();
		legacyPhone.setPhoneNumber(this.primaryPhone);
		@SuppressWarnings("deprecation")
		Phone result = (phonePrimary == null && this.primaryPhone != null) ? legacyPhone : phonePrimary;

		if (result == null) {
			result = new PhoneImpl();
		}

		return result;
	}

	@Override
	public String getFullName() {
		return getLastName() == null ? getFirstName() : getLastName() + getFirstName();
	}
}
